from datetime import datetime, timedelta
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from sqlalchemy import and_, or_, func, desc
from app.models.treatment import TreatmentRecord, TreatmentTemplate
from app.models.user import User
from app.extensions import db
from app.utils.decorators import handle_errors
from app.utils.validators import validate_treatment_params

treatments_bp = Blueprint('treatments', __name__, url_prefix='/api/treatments')


@treatments_bp.route('', methods=['GET'])
@jwt_required()
@handle_errors
def get_treatments():
    """获取治疗记录列表"""
    current_user_id = get_jwt_identity()
    
    # 查询参数
    page = request.args.get('page', 1, type=int)
    pageSize = request.args.get('pageSize', 20, type=int)
    status = request.args.get('status')
    mode = request.args.get('mode')
    start_date = request.args.get('start_date')
    end_date = request.args.get('end_date')
    
    # 构建查询
    query = TreatmentRecord.query
    
    if status:
        query = query.filter(TreatmentRecord.status == status)
    if mode:
        query = query.filter(TreatmentRecord.treatment_mode == mode)
    if start_date:
        start_dt = datetime.fromisoformat(start_date)
        query = query.filter(TreatmentRecord.created_at >= start_dt)
    if end_date:
        end_dt = datetime.fromisoformat(end_date)
        query = query.filter(TreatmentRecord.created_at <= end_dt)
    
    # 分页查询
    query = query.order_by(desc(TreatmentRecord.created_at))
    total = query.count()
    records = query.offset((page - 1) * pageSize).limit(pageSize).all()
    
    return jsonify({
        'records': [record.to_dict() for record in records],
        'total': total,
        'page': page,
        'pageSize': pageSize,
        'pages': (total + pageSize - 1) // pageSize
    })


@treatments_bp.route('', methods=['POST'])
@jwt_required()
@handle_errors
def create_treatment():
    """创建治疗记录"""
    current_user_id = get_jwt_identity()
    data = request.get_json()
    
    # 验证治疗参数
    validation_error = validate_treatment_params(data)
    if validation_error:
        return jsonify({'error': validation_error}), 400
    
    # 创建治疗记录
    record = TreatmentRecord(
        user_id=current_user_id,
        device_id=data.get('device_id'),
        treatment_mode=data['treatment_mode'],
        current_intensity=data.get('current_intensity'),
        treatment_duration=data.get('treatment_duration'),
        frequency=data.get('frequency'),
        start_time=data.get('start_time'),
        end_time=data.get('end_time'),
        status=data.get('status', 'completed'),
        effectiveness_score=data.get('effectiveness_score'),
        notes=data.get('notes')
    )
    
    db.session.add(record)
    db.session.commit()
    
    return jsonify({
        'message': '治疗记录创建成功',
        'record': record.to_dict()
    })


@treatments_bp.route('/records', methods=['POST'])
@jwt_required()
@handle_errors
def create_treatment_record():
    """为小程序创建治疗记录（简化版）"""
    current_user_id = get_jwt_identity()
    data = request.get_json()
    
    # 创建治疗记录
    record = TreatmentRecord(
        user_id=current_user_id,
        device_id=data.get('device_id'),
        treatment_mode=data.get('treatment_mode', 'tDCS+'),
        current_intensity=data.get('current_intensity', 1.0),
        treatment_duration=data.get('treatment_duration', 20),
        frequency=data.get('frequency', 10.0),
        start_time=datetime.fromisoformat(data['start_time']) if data.get('start_time') else datetime.utcnow(),
        end_time=datetime.fromisoformat(data['end_time']) if data.get('end_time') else None,
        status=data.get('status', 'completed'),
        effectiveness_score=data.get('effectiveness_score'),
        notes=data.get('notes')
    )
    
    db.session.add(record)
    db.session.commit()
    
    return jsonify({
        'message': '治疗记录创建成功',
        'record': record.to_dict()
    }), 200


@treatments_bp.route('/records', methods=['GET'])
@jwt_required()
@handle_errors
def get_user_treatment_records():
    """获取当前用户的所有治疗记录"""
    current_user_id = get_jwt_identity()
    
    # 查询参数
    page = request.args.get('page', 1, type=int)
    pageSize = request.args.get('pageSize', 20, type=int)
    
    # 构建查询
    query = TreatmentRecord.query.filter_by(user_id=current_user_id)
    
    # 分页查询
    query = query.order_by(desc(TreatmentRecord.created_at))
    total = query.count()
    records = query.offset((page - 1) * pageSize).limit(pageSize).all()
    
    return jsonify({
        'records': [record.to_dict() for record in records],
        'total': total,
        'page': page,
        'pageSize': pageSize,
        'pages': (total + pageSize - 1) // pageSize
    })


@treatments_bp.route('/records/recent', methods=['GET'])
@jwt_required()
@handle_errors
def get_recent_treatment_records():
    """获取当前用户最近的治疗记录"""
    current_user_id = get_jwt_identity()
    
    # 获取最近10条记录
    records = TreatmentRecord.query.filter_by(user_id=current_user_id)\
        .order_by(desc(TreatmentRecord.created_at))\
        .limit(10).all()
    
    return jsonify({
        'records': [record.to_dict() for record in records]
    })
    
    record = TreatmentRecord.query.filter_by(
        id=record_id,
        user_id=current_user_id
    ).first()
    
    if not record:
        return jsonify({'error': '治疗记录不存在'}), 404
    
    return jsonify({
        'record': record.to_dict()
    })


@treatments_bp.route('/<int:record_id>', methods=['PUT'])
@jwt_required()
@handle_errors
def update_treatment(record_id):
    """更新治疗记录"""
    current_user_id = get_jwt_identity()
    
    record = TreatmentRecord.query.filter_by(
        id=record_id,
        user_id=current_user_id
    ).first()
    
    if not record:
        return jsonify({'error': '治疗记录不存在'}), 404
    
    data = request.get_json()
    
    # 更新允许的字段
    if 'effectiveness_score' in data:
        record.effectiveness_score = data['effectiveness_score']
    if 'notes' in data:
        record.notes = data['notes']
    if 'end_time' in data and data['end_time']:
        record.end_time = datetime.fromisoformat(data['end_time'])
    if 'status' in data:
        record.status = data['status']
    
    db.session.commit()
    
    return jsonify({
        'message': '治疗记录更新成功',
        'record': record.to_dict()
    })


@treatments_bp.route('/statistics', methods=['GET'])
@jwt_required()
@handle_errors
def get_statistics():
    """获取治疗统计数据"""
    current_user_id = get_jwt_identity()
    
    # 时间范围参数
    days = request.args.get('days', 30, type=int)
    start_date = datetime.utcnow() - timedelta(days=days)
    
    # 基础统计
    total_treatments = TreatmentRecord.query.filter_by(user_id=current_user_id).count()
    completed_treatments = TreatmentRecord.query.filter_by(
        user_id=current_user_id,
        status='completed'
    ).count()
    
    recent_treatments = TreatmentRecord.query.filter(
        and_(
            TreatmentRecord.user_id == current_user_id,
            TreatmentRecord.created_at >= start_date
        )
    ).count()
    
    # 模式统计
    mode_stats = db.session.query(
        TreatmentRecord.treatment_mode,
        func.count(TreatmentRecord.id).label('count')
    ).filter_by(user_id=current_user_id).group_by(TreatmentRecord.treatment_mode).all()
    
    # 每日治疗次数统计（最近30天）
    daily_stats = db.session.query(
        func.date(TreatmentRecord.created_at).label('date'),
        func.count(TreatmentRecord.id).label('count')
    ).filter(
        and_(
            TreatmentRecord.user_id == current_user_id,
            TreatmentRecord.created_at >= start_date
        )
    ).group_by(func.date(TreatmentRecord.created_at)).all()
    
    # 平均治疗强度
    avg_intensity = db.session.query(
        func.avg(TreatmentRecord.current_intensity)
    ).filter_by(user_id=current_user_id).scalar() or 0
    
    return jsonify({
        'total_treatments': total_treatments,
        'completed_treatments': completed_treatments,
        'completion_rate': (completed_treatments / total_treatments * 100) if total_treatments > 0 else 0,
        'recent_treatments': recent_treatments,
        'avg_intensity': round(float(avg_intensity), 1),
        'mode_distribution': [{'mode': mode, 'count': count} for mode, count in mode_stats],
        'daily_treatments': [{'date': str(date), 'count': count} for date, count in daily_stats]
    })


# 治疗模板相关接口
@treatments_bp.route('/templates', methods=['GET'])
@jwt_required()
@handle_errors
def get_templates():
    """获取治疗模板列表"""
    current_user_id = get_jwt_identity()
    template_type = request.args.get('template_type')  # 模板类型筛选参数
    type = request.args.get('type', 'system')  # 模板来源类型：system(系统) 或 user(用户)
    
    # 查询参数
    page = request.args.get('page', 1, type=int)
    pageSize = request.args.get('pageSize', 20, type=int)
    
    # 构建查询
    if type == 'system':
        query = TreatmentTemplate.query.filter_by(user_id=1)
    elif current_user_id == '1':
        query = TreatmentTemplate.query.filter(TreatmentTemplate.user_id!=1)
    else:
        query = TreatmentTemplate.query.filter_by(user_id=current_user_id)

    # 根据模板类型筛选
    if template_type:
        query = query.filter_by(template_type=template_type)
    
    # 分页查询
    query = query.order_by(desc(TreatmentTemplate.created_at))
    total = query.count()
    records = query.offset((page - 1) * pageSize).limit(pageSize).all()
    
    return jsonify({
        'records': [template.to_dict() for template in records],
        'total': total,
        'page': page,
        'pageSize': pageSize,
        'pages': (total + pageSize - 1) // pageSize
    })


@treatments_bp.route('/templates/user', methods=['GET'])
@jwt_required()
@handle_errors
def get_user_templates():
    """获取当前用户的所有治疗模板（不分页，用于小程序）"""
    current_user_id = get_jwt_identity()
    
    # 查询该用户的所有模板
    templates = TreatmentTemplate.query.filter_by(user_id=current_user_id) \
        .order_by(desc(TreatmentTemplate.is_default), desc(TreatmentTemplate.created_at)) \
        .all()
    
    return jsonify({
        'templates': [template.to_dict() for template in templates]
    })


@treatments_bp.route('/templates', methods=['POST'])
@jwt_required()
@handle_errors
def create_template():
    """创建治疗模板"""
    current_user_id = get_jwt_identity()
    data = request.get_json()
    uid = data.get('user_id', None)
    if uid:
        current_user_id = uid
    
    # 验证模板参数
    validation_error = validate_treatment_params(data)
    if validation_error:
        return jsonify({'error': validation_error}), 400
    
    template = TreatmentTemplate(
        user_id=current_user_id,
        template_name=data['template_name'],
        template_type=data.get('template_type', 'hospital'),
        treatment_mode=data['treatment_mode'],
        current_intensity=data.get('current_intensity'),
        treatment_duration=data.get('treatment_duration'),
        frequency=data.get('frequency'),
        is_default=data.get('is_default', False)
    )
    
    # 如果设置为默认模板，取消其他默认模板
    if template.is_default:
        TreatmentTemplate.query.filter_by(
            user_id=current_user_id,
            is_default=True
        ).update({'is_default': False})
    
    db.session.add(template)
    db.session.commit()
    
    return jsonify({
        'message': '治疗模板创建成功',
        'template': template.to_dict()
    })


@treatments_bp.route('/templates/<int:template_id>', methods=['PUT'])
@jwt_required()
@handle_errors
def update_template(template_id):
    """更新治疗模板"""
    current_user_id = get_jwt_identity()
    
    template = TreatmentTemplate.query.filter_by(
        id=template_id,
        user_id=current_user_id
    ).first()
    
    if not template:
        return jsonify({'error': '治疗模板不存在'}), 404
    
    data = request.get_json()
    
    # 更新允许的字段
    if 'template_name' in data:
        template.template_name = data['template_name']
    if 'template_type' in data:
        template.template_type = data['template_type']
    if 'treatment_mode' in data:
        template.treatment_mode = data['treatment_mode']
    if 'current_intensity' in data:
        template.current_intensity = data['current_intensity']
    if 'treatment_duration' in data:
        template.treatment_duration = data['treatment_duration']
    if 'frequency' in data:
        template.frequency = data['frequency']
    if 'is_default' in data:
        template.is_default = data['is_default']
        # 如果设置为默认模板，取消其他默认模板
        if template.is_default:
            TreatmentTemplate.query.filter_by(
                user_id=current_user_id,
                is_default=True
            ).update({'is_default': False})
    
    db.session.commit()
    
    return jsonify({
        'message': '治疗模板更新成功',
        'template': template.to_dict()
    })


@treatments_bp.route('/templates/by-type/<template_type>', methods=['GET'])
@jwt_required()
@handle_errors
def get_templates_by_type(template_type):
    """根据模板类型获取治疗模板"""
    current_user_id = get_jwt_identity()
    
    # 验证模板类型是否有效
    valid_types = ['hospital', 'school', 'enterprise', 'research']
    if template_type not in valid_types:
        return jsonify({'error': '无效的模板类型'}), 400
    
    # 查询该用户该类型的模板
    templates = TreatmentTemplate.query.filter_by(
        user_id=current_user_id,
        template_type=template_type
    ).order_by(desc(TreatmentTemplate.created_at)).all()
    
    return jsonify({
        'templates': [template.to_dict() for template in templates]
    })


@treatments_bp.route('/templates/<int:template_id>', methods=['DELETE'])
@jwt_required()
@handle_errors
def delete_template(template_id):
    """删除治疗模板"""
    current_user_id = get_jwt_identity()
    
    template = TreatmentTemplate.query.filter_by(
        id=template_id,
        user_id=current_user_id
    ).first()
    
    if not template:
        return jsonify({'error': '治疗模板不存在'}), 404
    
    db.session.delete(template)
    db.session.commit()
    
    return jsonify({'message': '治疗模板删除成功'})